Write a program that counts the number of substrings of S that are anagrams and T strings in S string. When identifying anagrams, case is sensitive. Substrings must be contiguous strings.
bacaAacba
abc
Outputs the number of substrings that become T strings and anagrams in S word.
3
Sort()
function solution(s, t) {
let answer = 0;
// sorted arr2
const arr2 = t.split('').sort();
for (let i = 0; i < s.length - (t.length - 1); i++) {
let arr1 = [];
for (let j = 0; j < t.length; j++) arr1.push(s[i + j]);
// sorted arr1
const sortedArr1 = arr1.sort();
// check validation
let isValid = true;
for (let k = 0; k < sortedArr1.length; k++) {
if (sortedArr1[k] !== arr2[k]) isValid = false;
}
if (isValid) answer++;
}
return answer;
}
Map().set()
& Map().get()
, Two pointer Algofunction compareMaps(map1, map2) {
if (map1.size !== map2.size) return false;
for (let [key, val] of map1) {
if (!map2.has(key) || map2.get(key) !== val) return false;
}
return true;
}
function solution(s, t) {
let answer = 0,
sH = new Map(),
tH = new Map();
/** map setting */
for (let x of t) {
if (tH.has(x)) tH.set(x, tH.get(x) + 1);
else tH.set(x, 1);
}
let len = t.length - 1;
for (let i = 0; i < len; i++) {
if (sH.has(s[i])) sH.set(s[i], sH.get(s[i]) + 1);
else sH.set(s[i], 1);
}
/** sliding */
let lt = 0;
for (let rt = len; rt < s.length; rt++) {
if (sH.has(s[rt])) sH.set(s[rt], sH.get(s[rt]) + 1);
else sH.set(s[rt], 1);
if (compareMaps(sH, tH)) answer++;
// substract
sH.set(s[lt], sH.get(s[lt]) - 1);
if (sH.get(s[lt]) === 0) sH.delete(s[lt]);
lt++;
}
return answer;
}